package com.uchengwang.ui.cm_ui.cycle.ui;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aliyun.vodplayer.media.AliyunVidSts;
import com.aliyun.vodplayer.media.AliyunVodPlayer;
import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.aliyun.vodplayerview.utils.NetWatchdog;
import com.aliyun.vodplayerview.utils.ScreenUtils;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.release.bean.AliyunSTSTokenBean;
import com.uchengwang.ui.cm_ui.release.utils.VideoManagerUtils;
import com.uchengwang.ui.utils.DateUtil;
import com.uchengwang.ui.utils.UCommonUtil;

import java.lang.ref.WeakReference;

/**
 * Created by U城网 on 2018/5/15.
 * 自定义视频播放界面
 */

public class PlayVideoCustomActivity extends AllBaseActivity implements View.OnClickListener{
    private static final String TAG = PlayVideoCustomActivity.class.getSimpleName();

    private SurfaceView surfaceView;

    private TextView positionTxt;
    private TextView durationTxt;
    private SeekBar progressBar;
    private ImageView custom_finish, custom_play;



    private AliyunVodPlayer aliyunVodPlayer;

    private boolean inSeek = false;
    private boolean isCompleted = false;

    private String mVid = null;
    private AliyunVidSts mVidSts = null;
    private NetWatchdog netWatchdog;
    private long videoTime, currentTime;//视频长度 单位毫秒
    private boolean isPlay;// 当前是否在播放
    private IAliyunVodPlayer.PlayerState state;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mVid = getIntent().getStringExtra(BaseConfig.VIDEO_ID);

        setContentView(R.layout.activity_play_video_custom);
        surfaceView = (SurfaceView) findViewById(R.id.custom_surface);
        surfaceView.setOnClickListener(this);


        positionTxt = (TextView) findViewById(R.id.custom_currentPosition);
        durationTxt = (TextView) findViewById(R.id.custom_totalDuration);
        progressBar = (SeekBar) findViewById(R.id.custom_progress);
        custom_finish = (ImageView) findViewById(R.id.custom_finish);
        custom_finish.setOnClickListener(this);

        custom_play = (ImageView) findViewById(R.id.custom_play);
        custom_play.setOnClickListener(this);

        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 触发操作，拖动 跳转到指定时间点的视频画面，时间单位为秒
//                if (isSeekBarDrag){
//                    int currentSecond = (int) ((videoTime/1000) *progress/100);
//                    Log.d("jjf", "进度=="+progress+"==当前=="+currentSecond);
//                    aliyunVodPlayer.seekTo(currentSecond);
//                }
                Log.d("jjf", "播放状态=="+aliyunVodPlayer.getPlayerState());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 表示进度条刚开始拖动，开始拖动时候触发的操作
//                progressUpdateTimer.removeMessages(0);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //停止拖动

                if (aliyunVodPlayer != null) {
                    int currentSecond = (int) ((videoTime/1000) *seekBar.getProgress()/100);
                    Log.d("jjf", "停止拖动时的进度=="+currentSecond);

                    Log.d("jjf", "播放状态=="+aliyunVodPlayer.getPlayerState());
                    prepareAsync(currentSecond);
//                    if (currentSecond < videoTime/1000){
//                        //说明当前的进度时间不在最后
//                        showVideoProgressInfo();
//                    }
                    if (isCompleted) {
                        //播放完成了，不能seek了
                        inSeek = false;
                        isCompleted = false;
                    } else {
                        inSeek = true;
                    }
                }
            }
        });


        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d(TAG, "surfaceCreated");
                aliyunVodPlayer.setDisplay(holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG, "surfaceChanged");
                aliyunVodPlayer.surfaceChanged();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.d(TAG, "surfaceDestroyed");
            }
        });


        initVodPlayer();
        setPlaySource();

        netWatchdog = new NetWatchdog(this);

        netWatchdog.setNetChangeListener(new MyNetChangeListener(this));
        netWatchdog.startWatch();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.custom_surface:
                if (custom_play.getVisibility() ==View.GONE){
                    state = aliyunVodPlayer.getPlayerState();
                    custom_play.setVisibility(View.VISIBLE);
                    switch (state){
                        case Started:
                            ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_stop, ImageManager.ImageType.NARMOL);
                            break;
                        default:
                            ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_play, ImageManager.ImageType.NARMOL);
                            break;
                    }
                    progressUpdateTimer.sendEmptyMessageDelayed(1, 2000);
                }else {
                    custom_play.setVisibility(View.GONE);
                }
                break;
            case R.id.custom_finish:
                //finish界面
                finish();
                break;
            case R.id.custom_play:
                //播放或者隐藏
                state = aliyunVodPlayer.getPlayerState();
                switch (state){
                    case Started://当前是播放状态
                        aliyunVodPlayer.pause();
                        ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_play, ImageManager.ImageType.NARMOL);
                        break;
                    case Paused://当前是暂停状态
                        aliyunVodPlayer.start();
                        ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_stop, ImageManager.ImageType.NARMOL);
                        break;
                    case Released://释放状态
                        prepareAsync(0);
                        ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_play, ImageManager.ImageType.NARMOL);
                        break;
                    case Completed://播放完成
                        prepareAsync(0);
                        ImageManager.getInstance().loadImage(this, custom_play, R.drawable.icon_video_play, ImageManager.ImageType.NARMOL);
                        break;
                }

                break;
        }
    }

    private static class MyNetChangeListener implements NetWatchdog.NetChangeListener {

        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyNetChangeListener(PlayVideoCustomActivity activity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(activity);
        }

        @Override
        public void onWifiTo4G(){
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if(activity != null){
                activity.onWifiTo4G();
            }
        }

        @Override
        public void on4GToWifi() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if(activity != null){
                activity.on4GToWifi();
            }
        }

        @Override
        public void onNetDisconnected() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if(activity != null){
                activity.onNetDisconnected();
            }
        }
    }

    private void onWifiTo4G() {
        UCommonUtil.getUtil().showToast(this, "当前网络为4G");
    }

    private void on4GToWifi() {
//        UCommonUtil.getUtil().showToast(this, "当前网络为wifi");
    }

    private void onNetDisconnected() {
        UCommonUtil.getUtil().showToast(this, "当前网络为4G");
    }

    /**
     * @param toSeek 秒  跳转到多少秒
     * */
    private void prepareAsync(int toSeek) {
        aliyunVodPlayer.prepareAsync(mVidSts);
        aliyunVodPlayer.start();

        if (toSeek >0){
            aliyunVodPlayer.seekTo(toSeek*1000);
        }

        //获取播放的当前时间，单位为秒
        currentTime = aliyunVodPlayer.getCurrentPosition();
        //获取视频的总时长，单位为秒
        videoTime = aliyunVodPlayer.getDuration();
    }

    private void initVodPlayer() {
        aliyunVodPlayer = new AliyunVodPlayer(this);
        String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ali_save_cache";
        aliyunVodPlayer.setPlayingCache(true, sdDir, 60 * 60 , 300 );
        aliyunVodPlayer.setCirclePlay(false);//是否循环播放

//        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);

        aliyunVodPlayer.setOnCircleStartListener(new MyCircleStartListener(this));
        aliyunVodPlayer.setOnPreparedListener(new MyPrepareListener(this));
        aliyunVodPlayer.setOnFirstFrameStartListener(new MyFirstFrameListener(this));
        aliyunVodPlayer.setOnErrorListener(new MyErrorListener(this));
        aliyunVodPlayer.setOnCompletionListener(new MyCompletionListener(this));
        aliyunVodPlayer.setOnSeekCompleteListener(new MySeekCompleteListener(this));
        aliyunVodPlayer.setOnStoppedListner(new MyStoppedListener(this));

        aliyunVodPlayer.setOnUrlTimeExpiredListener(new MyUrlTimeExpriedListener(this));
        aliyunVodPlayer.enableNativeLog();
    }

    private static class MyUrlTimeExpriedListener implements IAliyunVodPlayer.OnUrlTimeExpiredListener {
        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyUrlTimeExpriedListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onUrlTimeExpired(String vid, String quality) {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onUrlTimeExpired(vid, quality);
            }
        }
    }

    private long urlExpiredPostion = 0;
    private IAliyunVodPlayer.PlayerState urlExpiredState = null;

    private void onUrlTimeExpired(String vid, String quality) {
        urlExpiredPostion = aliyunVodPlayer.getCurrentPosition();
        urlExpiredState = aliyunVodPlayer.getPlayerState();
        setPlaySource();
        aliyunVodPlayer.stop();
        aliyunVodPlayer.seekTo((int) urlExpiredPostion);
        prepareAsync(0);
    }

    private static class MyCircleStartListener implements IAliyunVodPlayer.OnCircleStartListener {
        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyCircleStartListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onCircleStart() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onCircleStart();
            }
        }
    }

    private void onCircleStart() {
        //循环播放开始
    }

    private static class MyPrepareListener implements IAliyunVodPlayer.OnPreparedListener {

        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyPrepareListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onPrepared() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onPrepared();
            }
        }
    }

    private void onPrepared() {
        aliyunVodPlayer.start();

        //获取播放的当前时间，单位为毫秒
        currentTime = aliyunVodPlayer.getCurrentPosition();
        //获取视频的总时长，单位为毫秒
        videoTime = aliyunVodPlayer.getDuration();

        Log.d("jjf", "视频时间长短="+videoTime+"==当前时间=="+currentTime);
    }

    private static class MyFirstFrameListener implements IAliyunVodPlayer.OnFirstFrameStartListener {

        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyFirstFrameListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onFirstFrameStart() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onFirstFrameStart();
            }
        }
    }
    //视频开始播放

    private void onFirstFrameStart() {
        showVideoProgressInfo();

    }

    private static class MyErrorListener implements IAliyunVodPlayer.OnErrorListener {

        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyErrorListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onError(int arg0, int arg1, String msg) {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onError(arg0, arg1, msg);
            }
        }
    }

    private void onError(int arg0, int arg1, String msg) {

    }

    private static class MyCompletionListener implements IAliyunVodPlayer.OnCompletionListener {
        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyCompletionListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onCompletion() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onCompletion();
            }
        }
    }

    private void onCompletion() {
        Log.d("jjf", "播放状态=="+aliyunVodPlayer.getPlayerState());
        isCompleted = true;
        inSeek = false;
        showVideoProgressInfo();
        stopUpdateTimer();
    }

    private static class MySeekCompleteListener implements IAliyunVodPlayer.OnSeekCompleteListener {

        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MySeekCompleteListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }

        @Override
        public void onSeekComplete() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onSeekComplete();
            }
        }
    }

    private void onSeekComplete() {
//        logStrs.add(format.format(new Date()) + getString(R.string.log_seek_completed));
        inSeek = false;
    }

    private static class MyStoppedListener implements IAliyunVodPlayer.OnStoppedListener {
        private WeakReference<PlayVideoCustomActivity> activityWeakReference;

        public MyStoppedListener(PlayVideoCustomActivity skinActivity) {
            activityWeakReference = new WeakReference<PlayVideoCustomActivity>(skinActivity);
        }


        @Override
        public void onStopped() {
            PlayVideoCustomActivity activity = activityWeakReference.get();
            if (activity != null) {
                activity.onStopped();
            }
        }
    }

    private void onStopped() {

    }


    private void setPlaySource() {

        VideoManagerUtils.getUtils().getVideoSTS(this, null, new OnHttpResultSingleListener<AliyunSTSTokenBean>() {
            @Override
            public void onResult(int status, String msg, AliyunSTSTokenBean bean) {
                if (bean != null ){
                    mVidSts = new AliyunVidSts();
                    mVidSts.setVid(mVid);
                    mVidSts.setAcId(bean.getAccessKeyId());
                    mVidSts.setAkSceret(bean.getAccessKeySecret());
                    mVidSts.setSecurityToken(bean.getSecurityToken());
                    //开始播放

                   prepareAsync(0);

                }
            }
        });
    }

    //显示视频进度信息
    private void showVideoProgressInfo() {
        if (aliyunVodPlayer != null && !inSeek) {
            int curPosition = (int) aliyunVodPlayer.getCurrentPosition();
            positionTxt.setText(DateUtil.getDateUtil().getTimeMS(curPosition));
            int duration = (int) aliyunVodPlayer.getDuration();
            durationTxt.setText(DateUtil.getDateUtil().getTimeMS(duration));
            Log.d("jjf", "更新seekBar duration = " + duration + " , curPosition = " + curPosition);
            int bufferPosition = aliyunVodPlayer.getBufferingPosition();
//            progressBar.setMax(100);
            progressBar.setSecondaryProgress(bufferPosition);
            int p = (int) (curPosition*100/videoTime);
            Log.d("jjf", "当前进度=="+p);
            progressBar.setProgress(p);
        }
        startUpdateTimer();
    }

    //开始显示
    private void startUpdateTimer() {
        Log.d(TAG, "setUpdaterListener--- ");
        progressUpdateTimer.removeMessages(0);
        progressUpdateTimer.sendEmptyMessageDelayed(0, 1000);
    }

    private void stopUpdateTimer() {
        progressUpdateTimer.removeMessages(0);
    }

    private MyHandler progressUpdateTimer = new MyHandler(this);

    @Override
    protected void onResume() {
        super.onResume();
        //保存播放器的状态，供resume恢复使用。
        resumePlayerState();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //onStop中记录下来的状态，在这里恢复使用
        savePlayerState();
    }


    //用来记录前后台切换时的状态，以供恢复。
    private IAliyunVodPlayer.PlayerState mPlayerState;

    private void resumePlayerState() {
        IAliyunVodPlayer.PlayerState playerState = aliyunVodPlayer.getPlayerState();
        if (playerState == IAliyunVodPlayer.PlayerState.Started ||
                playerState == IAliyunVodPlayer.PlayerState.Paused) {
            aliyunVodPlayer.start();
//            pauseBtn.setText(R.string.pause_button);
        }
    }

    private void savePlayerState() {
        if (aliyunVodPlayer.isPlaying()) {
            //然后再暂停播放器
            aliyunVodPlayer.pause();
//            pauseBtn.setText(R.string.resume_button);
        }
    }

    @Override
    protected void onDestroy() {
        aliyunVodPlayer.stop();
        aliyunVodPlayer.release();
        stopUpdateTimer();
        progressUpdateTimer = null;

        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {                //转为竖屏了。
            //显示状态栏
            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            //设置view的布局，宽高之类
            ViewGroup.LayoutParams surfaceViewLayoutParams = surfaceView.getLayoutParams();
            surfaceViewLayoutParams.height = (int) (ScreenUtils.getWidth(this) * 9.0f / 16);
            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;

        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {                //转到横屏了。
            //隐藏状态栏
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            surfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
            //设置view的布局，宽高
            ViewGroup.LayoutParams surfaceViewLayoutParams = surfaceView.getLayoutParams();
            surfaceViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;

        }
    }

    private static class MyHandler extends Handler{
        private WeakReference<PlayVideoCustomActivity> weakReference;
        public MyHandler (PlayVideoCustomActivity activity){
            weakReference = new WeakReference<PlayVideoCustomActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PlayVideoCustomActivity activity = weakReference.get();
            switch (msg.what){
                case 0:
                    activity.showVideoProgressInfo();
                    break;
                case 1:
                    //将显示的播放暂停按钮  隐藏
                    activity.custom_play.setVisibility(View.GONE);
                    break;
            }
        }
    }

}
